package com.asj.vivo.lock.receiver;

import static com.asj.enums.DeviceIdentifierDictEnums.json_key_deviceCode;
import static com.asj.enums.HttpRequestDictEnums.receiveNetworkLogInfo;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.asj.mq.ReceiveMessageTask;
import com.asj.service.oppoSdk.OPPOSDKService;
import com.asj.utils.CommonsUtils;
import com.asj.utils.HttpRequestUtils;
import com.google.gson.JsonObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 监听网络状态
 * */
public class NetworkChangeReceiver extends BroadcastReceiver {
    private static final Logger log = LoggerFactory.getLogger(NetworkChangeReceiver.class);

    @SuppressLint("StaticFieldLeak")
    private static  NetworkChangeReceiver networkChangeReceiver;
    @SuppressLint("StaticFieldLeak")
    private static Context registeredContext;

    //记录发送网络断开的通知id
    private int notificationId = 0;

    private static  LocalDateTime networkOutageLocalDateTime;

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
            // 网络已连接
            System.out.println("网络已连接！");

            networkLog(true, context);
            if(notificationId != 0){
                //关闭上一次的通知
                CommonsUtils.cancelNotificationById(context,notificationId);
                //重制notificationId = 0
                notificationId = 0;
            }
        } else {
            System.out.println("网络已断开！");

            networkLog(false, context);
            //发送网络断开通知
            notificationId = CommonsUtils.showNotification(context, "网络已断开", "建议连接上网络使用设备");
        }
    }
    public void networkLog(boolean isNetwork, Context context) {
        if (isNetwork) {
            // 设置网络当前连接时间
            LocalDateTime networkConnectLocalDateTime = LocalDateTime.now();
            if (networkOutageLocalDateTime != null) {
                // 计算网络断开时长
                Duration duration = Duration.between(networkOutageLocalDateTime, networkConnectLocalDateTime);
                long timeSecond = duration.getSeconds();

                JsonObject requestParam = new JsonObject();
                requestParam.addProperty("timeCount", String.valueOf(timeSecond));
                requestParam.addProperty("outageTime", String.valueOf(networkOutageLocalDateTime));
                requestParam.addProperty("connectionTime", String.valueOf(networkConnectLocalDateTime));
                requestParam.addProperty(json_key_deviceCode.getValue(), getIMEI(context));

                // 发生网络变化，就将情况发送给后端接收
                try {
                    new Thread(() -> HttpRequestUtils.retryHttpRequest(receiveNetworkLogInfo.getValue(), requestParam.toString(), 200, 3, context)).start();
                } catch (Exception e) {
                    log.error("发送网络波动状态请求异常！::{}", e.getMessage());
                }

                // 重置时间变量
                networkOutageLocalDateTime = null;

                /* 设立MQ监听服务 */
                ReceiveMessageTask.startMQService();
            }
        } else {
            networkOutageLocalDateTime = LocalDateTime.now();

            /* 关闭MQ监听服务 */
            ReceiveMessageTask.stopMQService();
        }
    }

    /**
     * 获取IMEI
     * */
    public static String getIMEI(Context context){
        return CommonsUtils.getDeviceCode(new OPPOSDKService(context).getIMEI());
    }

    /**
     * 注册网络状态监听器
     * */
    public static void startListening(Context context) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        if(networkChangeReceiver == null){
            networkChangeReceiver = new NetworkChangeReceiver();
            context.registerReceiver(networkChangeReceiver, filter);
            log.warn("网络监听器已注册");
//            CommonsUtils.showNotification(context,"网络监听已设置","这将会监听您设备的网络情况");
            //赋予值
            registeredContext = context;
        }
    }

    /**
     * 销毁网络状态监听器
     * */
    public static void stopListening() {
        if (networkChangeReceiver != null && registeredContext != null) {
            try {
                registeredContext.unregisterReceiver(networkChangeReceiver);
                log.warn("网络监听器已销毁");
            } catch (IllegalArgumentException e) {
                log.error("注销网络监听器时出现异常", e);
            } finally {
                networkChangeReceiver = null;
                registeredContext = null; // 释放引用避免泄漏
            }
        }
    }
}